﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Asah.SiteWorx.ProductCatalog;
using Asah.SiteWorx.Search;
using System.Data;

public partial class Search : BasePage
{
    private int _thumbnailSize = 0;
    private string _targetDirectory = HttpContext.Current.Server.MapPath("~/");
    private UserSearch _userSearch;

    /// <summary>
    /// This readonly property stores all of the valid pages (objects) that
    /// can be searched within the website.
    /// </summary>
    protected string[] SearchObjects
    {
        get
        {
            char[] commaSplitter = {','};
            string[] searchObjects = ConfigurationManager.AppSettings["SearchObjects"].Split(commaSplitter);
            return searchObjects;
        }
    }

    protected int ThumbnailSize
    {
        get
        {
            if (_thumbnailSize <= 0)
                if (ConfigurationManager.AppSettings["ProductCatalogThumbDefaultSize"] != null &&
                    ConfigurationManager.AppSettings["ProductCatalogThumbDefaultSize"].ToString().Length > 0)
                    _thumbnailSize = int.Parse(ConfigurationManager.AppSettings["ProductCatalogThumbDefaultSize"].ToString());
            return _thumbnailSize;
        }
    }

    public Search()
    {
        PreRender += new EventHandler(Page_PreRender);
    }

    /// <summary>
    /// When the page initally loads we check to see if there is
    /// a search string in memory that we need to process.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // first we need to hide the search box control if on the master page.
            if (Page.Master.FindControl("ctlSearchBox") != null)
                Page.Master.FindControl("ctlSearchBox").Visible = false;

            if (Session["SearchString"] != null)
                if (Session["SearchString"].ToString() != "")
                    if (Session["SearchString"].ToString() != ConfigurationManager.AppSettings["SearchDefaultText"].ToString())
                        DoSearch(Session["SearchString"].ToString().Trim());
            Session["SearchString"] = "";
        }
    }

    /// <summary>
    /// When the page prerenders we need to update our crumb control
    /// and let it append the search screen to it.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void Page_PreRender(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // need to update the crumb control.
            if (Page.Master.FindControl("ctlCrumbNavigation") != null)
                ((App_Common_UserControls_CrumbNavigation)Page.Master.FindControl("ctlCrumbNavigation")).AppendCrumb("Search Results", "");
        }
    }

    /// <summary>
    /// This function contains the code needed to search
    /// the website based off the search string passed in.
    /// </summary>
    /// <param name="search"></param>
    /// <returns></returns>
    private UserSearch SearchSite(string search)
    {
        UserSearch srchSite = new UserSearch();
        // read in all the search words into one variable.
        srchSite.SearchWords = search;

        if (Phrase.Checked)
            srchSite.SearchCriteria = SearchCriteria.Phrase;
        else if (AllWords.Checked)
            srchSite.SearchCriteria = SearchCriteria.AllWords;
        else if (AnyWords.Checked)
            srchSite.SearchCriteria = SearchCriteria.AnyWords;

        srchSite.Search(_targetDirectory);
        return srchSite;
    }

    /// <summary>
    /// This routine builds the results datagrid that is used
    /// to display all of the search results.
    /// </summary>
    /// <param name="sortField"></param>
    private void BindDataGrid(string sortField)
    {
        DataView dvwPages;
        dvwPages = _userSearch.PageDataset.Tables["Pages"].DefaultView;
        dvwPages.Sort = sortField;
        dgdPages.DataSource = dvwPages;
        dgdPages.DataBind();

        if (dgdPages.PageCount == 1)
            dgdPages.PagerStyle.Visible = false;
        else
            dgdPages.PagerStyle.Visible = true;

    }

    protected void dgdPages_SortCommand(object source, DataGridSortCommandEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        DisplayContent();
    }
    protected void dgdPages_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        dgdPages.CurrentPageIndex = e.NewPageIndex;
        DisplayContent();
    }

    protected string DisplayTitle(string title, string path)
    {
        return String.Format("<a href='{1}'>{0}</a>", title, path);
    }

    protected string DisplayPath(string path)
    {
        return String.Format("{0}{1}/{2}", Request.ServerVariables["HTTP_HOST"], Request.ApplicationPath, path);
    }
     
    private void DoSearch(string searchString)
    {
        string searchWords;

        // if there is no words entered by the user to search for then
        // don't carryout the file search routine.
        pnlSearchResults.Visible = false;
        pnlProductSearchResults.Visible = false;
        searchWords = searchString;

        if (searchWords.Length > 0)
        {
            foreach (string searchType in SearchObjects)
            {
                switch (searchType.ToLower())
                {
                    case "pages":
                        // page search
                        _userSearch = SearchSite(searchWords);
                        Session["Site"] = _userSearch;
                        dgdPages.CurrentPageIndex = 0;
                        DisplayContent();
                        break;
                    case "products":
                        // product search
                        dgdProducts.CurrentPageIndex = 0;
                        DoProductSearch(searchString);
                        break;
                }
            }
        }
    }

    private void DisplayContent()
    {
        if (_userSearch.PageDataset != null)
        {
            pnlSearchResults.Visible = true;
            lblSearchWords.Text = _userSearch.SearchWords;

            if (ViewState["SortExpression"] == null)
                ViewState["SortExpression"] = "MatchCount Desc";

            BindDataGrid(ViewState["SortExpression"].ToString());
            lblTotalFiles.Text = _userSearch.TotalFilesSearched.ToString();
            lblFilesFound.Text = _userSearch.TotalFilesFound.ToString();
        }
    }

    private void DoProductSearch(string searchString)
    {
        ProductList productList = ProductList.SearchProductList(searchString);
        if (productList.Count > 0)
        {
            pnlProductSearchResults.Visible = true;
            lblProductSearchWords.Text = searchString;

            Session["SearchedProducts"] = productList;
            dgdProducts.DataSource = productList;
            dgdProducts.DataBind();

            lblProductsFound.Text = productList.Count.ToString();
        }
    }

    protected void dgdProducts_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "Select")
            Response.Redirect("~/ProductDetail.aspx?id=" + e.CommandArgument, true);
    }
    protected void dgdProducts_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        dgdProducts.CurrentPageIndex = e.NewPageIndex;
        dgdProducts.DataSource = (ProductList)Session["SearchedProducts"];
        dgdProducts.DataBind();
    }
    protected void btnAdvSearch_Click(object sender, EventArgs e)
    {
        DoSearch(txtSearch.Text.Trim());
    }
   
}
